//
//  SEGFinishActivityTaskDetailViewController.m
//  SEGActivity
//
//  Created by 乔杨 on 2020/7/29.
//

#import "SEGFinishActivityTaskDetailViewController.h"

#import "SEGActivityTaskDetailCell.h"

#import <SEGViewModel/SEGSignActivityDetailViewModel.h>
#import "SEGTarget_ActivityManage.h"

@interface SEGFinishActivityTaskDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *titleDescLab;
@property (nonatomic, strong) UILabel *mainTaskLab;
@property (nonatomic, strong) UILabel *priceTipLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *endDateLabel;
@property (nonatomic, strong) UILabel *taskDesLabel;
@property (nonatomic, strong) UIView *tableFooterView;
@property (nonatomic, strong) UIButton *taskBtn;

@property (nonatomic, strong) SEGActivityTaskModel *taskModel;
/// 取消信号
@property (nonatomic, strong) RACDisposable *disposable;
/// viewModel
@property (nonatomic, strong) SEGSignActivityDetailViewModel *viewModel;

@end

@implementation SEGFinishActivityTaskDetailViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self seg_refresh];
}
 
#pragma mark - Load Data
- (void)seg_refresh {
    @weakify(self);
    [self.disposable dispose];
    self.viewModel.taskDetailCommand.allowsConcurrentExecution = YES;
    self.disposable = [[self.viewModel.taskDetailCommand execute:self.exampleId] subscribeNext:^(SEGActivityTaskModel *model) {
        @strongify(self);
        self.taskModel = model;
        [self updateUI];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

#pragma mark - UI
- (void)creatUI {
    self.view.backgroundColor = kColor_bg3;
    // bg
    UIView *contanerView = [[UIView alloc] init];
    contanerView.backgroundColor = kColor_W2;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight()*0.7) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(15,15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight()*0.7);
    maskLayer.path = maskPath.CGPath;
    contanerView.layer.mask = maskLayer;
    [self.view addSubview:contanerView];
    [contanerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(LYScreenHeight()*0.7);
    }];
    
    // 抽奖icon
    UIImageView *headerImageView = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_fuli_Popup_header")];
        [self.view addSubview:imageView];
        imageView;
    });
    [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(contanerView.mas_top);
    }];
    
    // 关闭action
    UIButton *tapButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:button];
        button;
    });
    [tapButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.equalTo(contanerView.mas_top);
    }];
    @weakify(self);
    [[tapButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    // 黄色header
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = UIColor.clearColor;
    [contanerView addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.height.mas_equalTo(75*kScaleWidth);
    }];
    UIImageView *yellowImageView = ({
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"pic_fuli_Popup_top02")];
        [headerView addSubview:imageView];
        imageView;
    });
    [yellowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    // 标题
    self.titleLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.textColor = kColor_W;
        label.font = [UIFont boldSystemFontOfSize:17];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = self.completeTaskTitle;
        [headerView addSubview:label];
        label;
    });
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView);
        make.left.equalTo(headerView).offset(53);
        make.right.equalTo(headerView).offset(-53);
        make.height.mas_equalTo(36*kScaleWidth);
    }];
    
    // 标题描述
    self.titleDescLab = ({
        UILabel *label = [[UILabel alloc] init];
        label.textColor = kColor_W;
        label.font = kFont_12;
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 2;
        label.text = self.completeTaskDesc;
        [headerView addSubview:label];
        label;
    });
    [self.titleDescLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom);
        make.left.right.centerX.equalTo(self.titleLabel);
    }];
        
    // 关闭按钮
    UIButton *closeButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_fuli_delete")] forState:UIControlStateNormal];
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_fuli_delete")] forState:UIControlStateHighlighted];
        [headerView addSubview:button];
        button;
    });
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(30);
        make.top.mas_equalTo(6);
        make.right.mas_equalTo(-6);
    }];
    
    [[closeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    // tableView
    [contanerView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(headerView.mas_bottom);
    }];
    
    // tableHeaderView
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 50)];
    // 结束时间
    self.endDateLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.layer.masksToBounds = YES;
        label.textColor = kColor_C;
        label.font = kFont_11;
        [tableHeaderView addSubview:label];
        label;
    });
    [self.endDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.height.equalTo(tableHeaderView.mas_height);
    }];
    // 主任务title
    self.mainTaskLab = ({
        UILabel *label = [[UILabel alloc] init];
        label.textColor = kColor_1;
        label.layer.masksToBounds = YES;
        label.font = [UIFont boldSystemFontOfSize:17];
        [tableHeaderView addSubview:label];
        label;
    });
    [self.mainTaskLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.width.lessThanOrEqualTo(@(LYScreenWidth()-140));
        make.height.equalTo(tableHeaderView.mas_height);
    }];
    // 奖
    self.priceTipLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.text = @"奖";
        label.hidden = YES;
        label.textColor = UIColor.whiteColor;
        label.font = kFont_10;
        label.backgroundColor = kColor_S1;
        label.textAlignment = NSTextAlignmentCenter;
        label.layer.cornerRadius = 3;
        label.layer.masksToBounds = YES;
        [tableHeaderView addSubview:label];
        label;
    });
    [self.priceTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.mainTaskLab.mas_centerY);
        make.left.equalTo(self.mainTaskLab.mas_right).mas_offset(5);
        make.width.mas_equalTo(15);
        make.height.mas_equalTo(15);
    }];
    self.tableView.tableHeaderView = tableHeaderView;
    
    // 任务说明
    self.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 100)];
    self.taskDesLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.numberOfLines = 0;
        label.textColor = kColor_C;
        label.font = kFont_11;
        [self.tableFooterView addSubview:label];
        label;
    });
    [self.taskDesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.top.mas_equalTo(15);
    }];
    self.tableView.tableFooterView = self.tableFooterView;
    
    // 底部按钮
    self.taskBtn = ({
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.hidden = YES;
        btn.backgroundColor = kColor_T;
        btn.layer.cornerRadius = 2.f;
        btn.layer.masksToBounds = YES;
        [btn setTitleColor:kColor_1 forState:UIControlStateNormal];
        btn.titleLabel.font = kFont_16;
        [btn addTarget:self action:@selector(seg_taskButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [contanerView addSubview:btn];
        btn;
    });
    [self.taskBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(-10-LYSafeAreaBottom());
    }];
}
- (void)updateUI {
    // 主任务title
    self.titleLabel.text = self.completeTaskTitle;
    self.titleDescLab.text = self.completeTaskDesc;
    self.priceTipLabel.hidden = (self.taskModel.whetherShowLottery == 1) ? NO:YES;
    self.mainTaskLab.text = self.taskModel.mainTaskTopic;
    [self.priceTipLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainTaskLab.mas_right).mas_offset(5);
    }];
    
    // endtime
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.taskModel.endTime.longLongValue];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    self.endDateLabel.text = [NSString stringWithFormat:@"%@结束", [formatter stringFromDate:date]];
    
    // rule
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[self.taskModel.mainTaskRule dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    self.taskDesLabel.attributedText = attributedString;
    CGRect desRect = [attributedString boundingRectWithSize:CGSizeMake(LYScreenWidth()-30, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    self.tableFooterView.frame = CGRectMake(0, 0, LYScreenWidth(), desRect.size.height + 30);
    
    // 底部按钮展示逻辑
    if (self.taskModel.whetherComplete == 2) { // 主任务 ”未完成“
        self.taskBtn.hidden = YES;
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
        }];
    } else if (self.taskModel.whetherComplete == 1) { // "已完成"
        NSString *taskBtnTitle = @"";
        if (self.lotteryId.integerValue > 0 && self.actId.integerValue >0 && self.triggerEventId.integerValue > 0) {
            taskBtnTitle = @"抽大奖";
        } else {
            taskBtnTitle = @"继续闯关";
            // 获取跳转福利社页面需要的“签到Id”
            [self.viewModel.signIdSignal subscribeNext:^(id  _Nullable x) {}];
        }
        self.taskBtn.hidden = NO;
        [self.taskBtn setTitle:taskBtnTitle forState:UIControlStateNormal];
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-64-LYSafeAreaBottom());
        }];
    }
    
    // reload
    [self.tableView reloadData];
}

#pragma mark - Event
- (void)seg_taskButtonAction:(UIButton *)button {
    if (self.taskModel.whetherComplete != 1) return;
    
    if (!self.presentingNav) return;
    if (self.lotteryId.integerValue > 0) { // 抽大奖
        [self dismissViewControllerAnimated:YES completion:^{
            UIViewController *LotteryVC = [[SEGUhomeMediator sharedInstance] seg_initActivityTriggerLotteryViewController:nil];
            [self.presentingNav pushViewController:LotteryVC animated:YES];
        }];

    } else { // "福利社"
        [self dismissViewControllerAnimated:YES completion:^{
            NSDictionary *dict = @{@"actId" : self.viewModel.signId};
            UIViewController *signVC = [[SEGUhomeMediator sharedInstance] seg_initActivitySignViewController:dict];
            [self.presentingNav pushViewController:signVC animated:YES];
        }];
    }
}
 
#pragma mark - <UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.taskModel.childTaskList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityTaskDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SEGActivityTaskDetailCell" forIndexPath:indexPath];
    [cell updateCellWithChildTaskModel:self.taskModel.childTaskList[indexPath.row]];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityChildTaskModel *childModel = self.taskModel.childTaskList[indexPath.row];
    if (self.presentingNav) {
        [SEGTarget_ActivityManage getActivityTaskSkipViewController:childModel presentVC:self nav:self.presentingNav];
    }
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.clearColor;
        [_tableView registerClass:[SEGActivityTaskDetailCell class] forCellReuseIdentifier:@"SEGActivityTaskDetailCell"];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom() + 30, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (SEGSignActivityDetailViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGSignActivityDetailViewModel new];
    return _viewModel;
}

@end
